package org.zfes.snowier.zbss.xzy.store.repository.db.mysql;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.zfes.snowier.core.util.ZObjectUtil;
import org.zfes.snowier.core.util.ZStrUtil;
import org.zfes.snowier.zbss.xzy.store.meta.TableMetaCache;
import org.zfes.snowier.zbss.xzy.store.repository.api.DataRepository;
import org.zfes.snowier.zbss.xzy.store.repository.api.StoreDataMsg;


public class MySqlRepository implements DataRepository {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired NamedParameterJdbcTemplate jdbcTemplate;
	
	@Autowired TableMetaCache tableMetaCache;
	
	@Autowired MysqlDDLService mysqlDDLService;
	
	@Override
	public void batchSave(String tablename, List<StoreDataMsg> dataListz) {
		//logger.info("-batchSave-1 -tablename:{},data-size:{}",tablename,dataListz.size());
		//logger.info("-batchSave-1 -tablename:{},dataListz:{}",tablename,dataListz);
		if(ZObjectUtil.isEmpty(dataListz)) {
			return;
		}
		List<Map<String, Object>> dataList=dataListz.stream().map(v->v.getDataMap()).collect(Collectors.toList());
		//logger.info("-batchSave-2 -tablename:{},dataList:{}",tablename,dataList.size());
		
		boolean isTableExists =tableMetaCache.isTableExists(tablename);
		Set<String> cachesColumns = tableMetaCache.getCols(tablename);
		Set<String> newAddColimns = dataList.stream().flatMap(v->v.keySet().stream()).collect(Collectors.toSet());
		
		Set<String> fullColumns = newAddColimns.stream().map(v->new String(v)).collect(Collectors.toSet());
				
		//logger.info("-batchSave- -isTableExists:{},cachesColumns:{},newAddColimns",isTableExists,cachesColumns,newAddColimns);
		
		if(isTableExists) {
			newAddColimns.removeAll(cachesColumns);
		}
		if(!newAddColimns.isEmpty()) {
			mysqlDDLService.refreshTable(tablename, newAddColimns);
			if(tablename.equals("zmd_device")) {
				mysqlDDLService.refreshTable(tablename+"_rt", newAddColimns);
			}
			if(tablename.equals("zmd_device_topo")) {
				mysqlDDLService.refreshTable(tablename+"_rt", newAddColimns);
			}
		
		}
		//少的列，补填充成空字符
		dataList.forEach(map->{
			Set<String> mapKeySet=map.keySet();
			Set<String> toBePlusSet =fullColumns.stream().filter(t-> !mapKeySet.contains(t)).collect(Collectors.toSet());
			 if(toBePlusSet!=null&&! toBePlusSet.isEmpty()) {
				 map.putAll(toBePlusSet.stream().collect(Collectors.toMap(key->key, val->"")));
			 }
			
		});
	
		String columns= ""+ZStrUtil.join(fullColumns, ",");
		String values = ":"+ZStrUtil.join(fullColumns, ", :");
		
		String sql=" insert into "+tablename+" ( "+ columns+" ) VALUES ( "+ values+")" ;
		
		//logger.info("-batchSave- -sql:{}",sql);
		
		
		@SuppressWarnings("unchecked")
		Map<String, Object>[] params =new HashMap[dataList.size()];// Maps.newHashMapWithExpectedSize(dataList.size());
		int size=dataList.size();
		for(int i=0;i<size;i++) {
			params[i]=dataList.get(i);
		}
		long a=System.currentTimeMillis();
		
		int[] res=jdbcTemplate.batchUpdate(sql,  params);
		
		long b=System.currentTimeMillis();
		
		logger.info("-batchSave- -time:{}",(b-a));
	}
	
//	public static void main(String[] args) {
//		Set<String> fullColumns = Sets.newHashSet("id","name","age","bg");
//		String columns=""+ZStrUtil.join(fullColumns, ",");
//		
//		String values =":"+ZStrUtil.join(fullColumns, ", :");
//		
//		System.out.println(columns);
//		System.out.println(values);
//
//	}

}
